directives.directive('tableAggregate',['$rootScope','tools','$timeout',function($rootScope,tools,$timeout){
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        templateUrl: '/trend-new-BI/app/components/dbManager/tableAggregate/tableAggregateView.html',
        link: function(scope, element, attr){

            scope.table1 = {}; //表1
            scope.table2 = {}; //表2
            scope.dataTable = null;
            scope.msg = null;  //错误提示

            //下拉框的个数--字段的关联--init
            scope.dataSum = [0];

            //存储选择的字段关联的信息---init
            scope.dataFileds = [{count:'count'}];

            //汇总分类的方式
            scope.counts = [
                {desc:'计数',value:'count'},
                {desc:'总和',value:'sum'},
                {desc:'最大值',value:'max'},
                {desc:'最小值',value:'min'},
                {desc:'平均值',value:'avg'},
                {desc:'分类',value:'group'}
            ];

            //init
            $rootScope.$on("saveAgg_EV",function(){
                //下拉框的个数--字段的关联--init
                scope.dataSum = null;
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = null;
                scope.dataFileds = [{count:'count'}];
            });

            //getOne
            $rootScope.$on("send_ONE_AGG_EV",function(e,json){
                //console.log(json);
                scope.dataFileds[0]={
                    filed:json.columnDesc,
                    filedDesc:json.columnDesc,
                    count:json.type
                };
                scope.addSum();
            });


            $rootScope.$on("tableAggregate_EV",function(e,table,data){
                $timeout(function(){
                    $(element).modal('show');
                },50);
              //  console.log(data);
                //表1
                scope.table1.value = table;

               // scope.table1.filed = data;
               // scope.dataTable = data;
                getFiled(scope.table1.value.tbId, scope.table1.value.tableType);
            });
            /**
             * 获取字段
             * @param tbId
             * @param tableType
             * @param index  第几个表 表1 or 表2
             */
            function getFiled(tbId, tableType) {
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getSingleTable.htm',
                    data: {
                        tbId: tbId,
                        tableType: tableType
                    },
                    succ: function (resp) {
                        if (resp.success) {

                           // scope.table1.filed = resp.value.columns;

                            scope.table1.filed = resp.value.columns;
                            scope.dataTable = resp.value.columns;
                            $timeout(function(){
                                $(".dropdown").dropdown();
                            },1000);
                        }else{
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            }

            //增加字段
            scope.addSum = function () {
                scope.dataFileds.push({count:'count'});
                scope.dataSum.push(scope.dataSum.length);
            };

            //删除字段
            scope.lessSum = function (index) {
                if(scope.dataSum.length==1){
                    return;
                }
                scope.dataSum.splice(index, 1);
                scope.dataFileds.splice(index, 1);
            };
            //scope.isGroup = false;
            scope.selectCount = function(index){
                scope.dataFileds[index].filedDesc = scope.dataFileds[index].filed;
                scope.dataFileds[index].isGroup = true;
            };

            //取消汇总
            scope.cancel = function () {
                $(element).modal('hide');

                scope.table1 = {}; //表1

                scope.msg = null;  //错误提示
                //下拉框的个数--字段的关联--init
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = [{}];

                $rootScope.$broadcast("cancel_aggAndShow_EV");

            };

            //确认汇总
            scope.ok = function(){

                if(scope.dataFileds[0].filed == null &&scope.dataFileds[0] != null){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }

                if(scope.dataFileds[0].count == null &&scope.dataFileds[0] != null){
                    scope.msg = '请选择聚合方式';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }

                for(var i=0;i<scope.dataFileds.length;i++){
                    for(var j=i+1;j<scope.dataFileds.length;j++){
                        if((scope.dataFileds[i].count == scope.dataFileds[j].count)&&(scope.dataFileds[j].count!=null) && (scope.dataFileds[i].filed == scope.dataFileds[j].filed) && (scope.dataFileds[j].filed != null)){
                            scope.msg = "该汇总分类已存在( 第"+(j+1)+"行 字段："+scope.dataFileds[j].filed+" ,聚合方式:"+scope.dataFileds[j].count+" )";
                            $timeout(function(){
                                scope.msg = null;
                            },2000);
                            return;
                        }
                    }
                }
               /* angular.forEach(scope.dataFileds,function(item){
                    if(item.count ==null || item.filed ==null ){
                        scope.msg = '请选择相应的字段和聚合方式';
                        $timeout(function(){
                            scope.msg = null;
                        },2000);
                        return;
                    }
                });*/


             //   console.log(scope.dataFileds);
              //  console.log(scope.table1.filed);


                $rootScope.$broadcast("loading_Start_EV");

                var json = {};
                //所有的字段选择信息----scope.dataFileds--从table中获取相应的值


                json.refTbId = scope.table1.value.tbId;
                json.refTableType = scope.table1.value.tableType;

                angular.forEach(scope.dataFileds, function (item) {//数组json

                    angular.forEach(scope.table1.filed, function (itemleft) {//table1
                        if (item.filed && item.filed == itemleft.columnDesc) {
                            item.filedData = {};
                            item.filedData.columnType = itemleft.columnType;
                            item.filedData.columnId = itemleft.columnId;
                            item.filedData.fieldName = itemleft.fieldName;
                            return;
                        }
                    });
                });



                json.columnDescs = '';
                json.fieldNames = '';
                json.aggregateTypes = '';
                json.columnTypes = '';
                json.refColumnIds = '';
                angular.forEach(scope.dataFileds,function(item){
                    if(item.filedData){ //去除空行的内容字段
                        json.fieldNames += item.filedData.fieldName+',';
                        json.aggregateTypes += item.count+',';

                        json.columnDescs += item.filedDesc+',';
                        json.columnTypes += item.filedData.columnType+',';
                        json.refColumnIds += item.filedData.columnId+',';
                    }

                });
                //console.log("分类汇总：")
               // console.log(json);

                $rootScope.$broadcast('addAggregateFunction_EV',json);
                $(element).modal('hide');

            };


        }
    }
}]);
